package com.weilai.service.serviceImpl;

import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.controller.exceptionHandler.SystemException;
import com.weilai.dao.CaptchaDao;
import com.weilai.domain.Captcha;
import com.weilai.service.CaptchaService;
import com.weilai.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Random;

@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private CaptchaDao captchaDao;

    @Autowired
    private EmailService emailService;

    @Override
    public Captcha getByEamil(String email) {
        try{
            return captchaDao.getByEamil(email);
        } catch (Exception e) {
            throw new BusinessException(Code.SYSTEM_DB_ERROR, "查找验证码时数据库出错");
        }

    }

    @Override
    public void sendCode(String email) {

        // 生成验证码
        Random random = new Random();
        int codeNum = random.nextInt(9000) + 1000;

        Captcha captcha = new Captcha();
        captcha.setEmail(email);
        captcha.setCreateAt(LocalDateTime.now());
        captcha.setCaptchaCode(codeNum);

        try{
            if(this.getByEamil(email)!=null){
                captchaDao.updateCode(captcha);
            }
            else{
                this.insertCaptcha(captcha);
            }
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_TIMEOUT_ERROR, "验证码发送时数据库出错", e);
        }

        try {
            // 发送验证码邮件
            emailService.sendMail(email, "【haven】",
                    "【haven】验证码" + codeNum + ",您正在登录haven,若非本人操作,请勿泄露,验证码仅在10分钟内有效");
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_TIMEOUT_ERROR, "验证码发送失败，请稍后重试", e);
        }
    }

    @Override
    public void insertCaptcha(Captcha captcha) {
        try{
            captchaDao.insertCaptcha(captcha);
        } catch (Exception e) {
            throw new BusinessException(Code.SYSTEM_DB_ERROR, "注册验证码时数据库出错");
        }
    }
}
